/**
 * AjLog - The AspectJ based logging facade
 *
 * Copyright (C) 2009 - 2010, Marko Umek. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.ajlog.core.message.segment;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.ajlog.core.message.IMessageParserResultCollector;
import org.ajlog.core.setup.IMessageParserNotifier;
import org.ajlog.core.setup.IStaticLoggingContext;
import org.ajlog.util.AjLogAssert;
import org.ajlog.util.AjLogLogger;
import org.apache.commons.lang.StringUtils;

/**
 * MessageSegmentFactory is responsible for creating {@link IMessageSegment}s
 * using {@link IMessageVariableParser}.
 * 
 * @author Marko Umek
 * 
 */
public class MessageSegmentFactory {
    /**
     * 
     */
    private static final String                       VALID_NAMESPACE_PATTERN = "[\\w.]*";

    /**
     * The namespace separator
     */
    static final String                               NAMESPACE_SEPARATOR     = ":";
    private static final AjLogLogger                  logger                  = AjLogLogger
                                                                                      .getLogger(MessageSegmentFactory.class);

    private final List<IMessageVariableParser>        noNamespaceParsers      = new LinkedList<IMessageVariableParser>();
    private final Map<String, IMessageVariableParser> namespaceParsers        = new HashMap<String, IMessageVariableParser>();
    private IMessageParserNotifier                    messageParserNotifier;
    private IStaticLoggingContext                     staticLoggingContext;

    /**
     * Constructor
     * 
     */
    public MessageSegmentFactory() {
    }

    /**
     * Setter for messageParserNotifier
     * 
     * @param messageParserNotifier
     *            the messageParserNotifier to set
     */
    public void setMessageParserNotifier(final IMessageParserNotifier messageParserNotifier) {
        this.messageParserNotifier = messageParserNotifier;
    }

    /**
     * Setter for staticLoggingContext
     * 
     * @param staticLoggingContext
     *            the staticLoggingContext to set
     */
    public void setStaticLoggingContext(final IStaticLoggingContext staticLoggingContext) {
        this.staticLoggingContext = staticLoggingContext;
    }

    /**
     * 
     * addMessageVariableParser adds the message variable parser.
     * 
     * @param messageVariableParser
     */
    public void addMessageVariableParser(final IMessageVariableParser messageVariableParser) {
        final String ns = this.validateNamespace(messageVariableParser.namespace());
        if (StringUtils.isEmpty(ns)) {
            this.noNamespaceParsers.add(messageVariableParser);
        }
        else {
            if (null != this.namespaceParsers.put(ns, messageVariableParser)) {
                logger.warn("Namespace parser (" + messageVariableParser + ") override existing namespace='%s'", ns);
            }
        }
    }

    /**
     * 
     * createMessageSegment is responsible for creating a message segment from
     * the variable value.
     * 
     * @param variableValue
     *            the variable value got from
     *            {@link IMessageParserResultCollector#appendVariable(String)}
     * 
     * @return the new message segment or <code>null</code> if the variable
     *         value has not been accepted by any {@link IMessageVariableParser}
     *         or no parser could be found.
     */
    public IMessageSegment createMessageSegment(final String variableValue) {
        try {
            final String[] splitResult = this.split(variableValue);
            String namespace = null;
            String variableValueNoNamespace = null;
            if (splitResult.length == 2) {
                namespace = splitResult[0];
                variableValueNoNamespace = splitResult[1];
            }
            else {
                variableValueNoNamespace = splitResult[0];
            }

            // Resolve the parser
            IMessageVariableParser parser = null;

            if (StringUtils.isNotEmpty(namespace)) {
                parser = this.resolveNamespaceParser(namespace, variableValueNoNamespace);
            }
            else {
                parser = this.resolveNoNamespaceParser(variableValueNoNamespace);
            }

            if (parser == null) {
                logger.error("No parser found for variable (value='%s')", variableValue);
                return null;
            }

            return parser.parse(variableValueNoNamespace, this.staticLoggingContext, this.messageParserNotifier);

        } catch (final Exception ex) {
            logger.error("Caught exception: %s", ex);
        }

        return null;
    }

    /**
     * Resolve the no namespace based parsers.
     */
    private IMessageVariableParser resolveNoNamespaceParser(final String variableValueNoNamespace) {
        logger.debug("Lookup for parser without namespace (value='%s')", variableValueNoNamespace);
        for (final IMessageVariableParser noNamespaceParser : this.noNamespaceParsers) {
            if (noNamespaceParser.accept(variableValueNoNamespace)) {
                return noNamespaceParser;
            }
            else {
                logger.debug("Variable (value='%s') has not been accepted", variableValueNoNamespace);
            }
        }
        return null;
    }

    /**
     * Resolve the namespace based parser
     */
    private IMessageVariableParser resolveNamespaceParser(final String namespace, final String variableValueNoNamespace) {
        logger.debug("Lookup for parser with namespace='%s' (value='%s')", namespace, variableValueNoNamespace);
        final IMessageVariableParser parser = this.namespaceParsers.get(namespace);
        if (parser != null) {
            if (!parser.accept(variableValueNoNamespace)) {
                logger.error("Variable content(%s) in namespace (%s) not accepted",
                        variableValueNoNamespace,
                        namespace
                        );
                return null;
            }
        }
        else {
            logger.error("No parser registered for namespace='%s'", namespace);
        }

        return parser;
    }

    /**
     * split variable into (namespace, variable value) or (variable)
     */
    private String[] split(final String variableValue) {
        final String[] result = StringUtils.split(variableValue, NAMESPACE_SEPARATOR, 2);
        if (result.length == 2) {
            result[0] = this.validateNamespace(result[0]);
        }

        return result;
    }

    /**
     * Validate the namespace. If not ok, an Exception will be thrown.
     * 
     */
    private String validateNamespace(final String namespace) {
        AjLogAssert.checkPattern(namespace, VALID_NAMESPACE_PATTERN, "Invalid namespace");
        return namespace;
    }
}
